<template>
	<view class="dishes-add">
		<u-navbar title="表单" @leftClick="leftClick" :autoBack="true"></u-navbar>
		<view class="dishes-add-container">
			<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
			<u--form labelPosition="left" :model="modelFormData" :rules="rules" ref="uForm">
				<u-form-item label="名称" prop="name" borderBottom ref="item_name">
					<u--input v-model="modelFormData.name" border="none" placeholder="请输入名称"></u--input>
				</u-form-item>
				<u-form-item label="类型" prop="type" borderBottom @click="showType = true; hideKeyboard()" ref="item_type">
					<u--input v-model="modelFormData.type" disabled disabledColor="#ffffff" placeholder="请选择类型"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="封面" prop="cover" borderBottom ref="item_cover">
					<FileUpload v-model="fileList" @success="fileUploadSuccess"></FileUpload>
				</u-form-item>
				<u-form-item label="配料" prop="ingredients" borderBottom ref="item_ingredients">
					<AddItems v-model="modelFormData.ingredients"></AddItems>
				</u-form-item>
				<u-form-item label="步骤" prop="steps" borderBottom ref="item_steps">
					<AddSteps v-model="modelFormData.steps"></AddSteps>
				</u-form-item>
				<u-form-item label="备注" prop="remarks" borderBottom ref="item_remarks">
					<u--textarea v-model="modelFormData.remarks" type="textarea" border="none" placeholder="请输入步骤具体内容"
						count></u--textarea>
				</u-form-item>
			</u--form>
			<view class="form-submit-box">
				<u-button :loading="submitLoading" type="primary" text="提 交" @click="submitForm"></u-button>
			</view>
		</view>
		<u-action-sheet :show="showType" :actions="actions" title="请选择类型" description="方便后续分类查找"
			@close="showType = false" @select="typeSelect">
		</u-action-sheet>
	</view>
</template>

<script>
	import FileUpload from './fileUpload.vue';
	import AddItems from './items.vue'
	import AddSteps from './steps.vue'
	import AuthorizationToken from '@/config/token.js'
	import baseUrl from '@/config/index.js'
	export default {
		components: {
			FileUpload,
			AddItems,
			AddSteps
		},
		data() {
			return {
				showType: false,
				modelFormData: {
					name: '',
					type: '',
					typeCode: '',
					cover: '',
					coverPath: '',
					coverPkid: '',
					ingredients: [],
					steps: [],
					remarks: ''
				},
				actions: [],
				rules: {
					'name': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					},
					'type': {
						type: 'string',
						max: 100,
						required: true,
						message: '请选择类型',
						trigger: ['blur', 'change']
					},
				},
				radio: '',
				switchVal: false,
				submitLoading: false,
				pkid: '',
				detailInfo: {},
				fileList: []
			};
		},
		onLoad(options) {
			this.pkid = options.pkid || ''
		},
		created() {
			this.getTypeList()
		},
		methods: {
			getDetailInfo() {
				const vm = this
				uni.request({
					header: {
						Authorization: AuthorizationToken
					},
					method: 'POST',
					url: baseUrl + '/agw/mongodb/table/data_v3',
					data: {
						pkid: vm.pkid,
						tablePkid: '4163d0000b7a4b2990392d5a534b7271'
					},
					success(res) {
						console.log('返回结果', res)
						vm.detailInfo = res.data?.data || {}
						vm.dishName = vm.detailInfo.name
						Object.assign(vm.modelFormData, vm.detailInfo)
						const t = vm.actions.find(i => {
							return vm.detailInfo.code === i.type
						})
						if (t) {
							vm.modelFormData.type = t.name
							vm.modelFormData.typeCode = t.code
						}
						if (Array.isArray(vm.detailInfo.cover)) {
							const _t = vm.detailInfo.cover[0] || {
								pkid: '',
								url: ''
							}
							vm.modelFormData.coverPath = _t.url
							vm.modelFormData.coverPkid = _t.pkid
							vm.fileList.length = 0
							vm.fileList.push({
								url: 'https://lyw.cdbytech.top:3017' + _t.url
							})
						}
						console.log('详情', vm.detailInfo)
					}
				})
			},
			getTypeList() {
				const dish_type = uni.getStorageSync('dish_type') || '[]'
				const dishTypeList = JSON.parse(dish_type)
				const list = dishTypeList.map(i => {
					return {
						name: i.label,
						code: i.code
					}
				})
				this.actions = [...this.actions, ...list]
				this.pkid && this.getDetailInfo()
			},
			typeSelect(e) {
				this.modelFormData.type = e.name
				this.modelFormData.typeCode = e.code
				this.$refs.uForm.validateField('type')
			},
			fileUploadSuccess(fileList) {
				console.log('上传成功的文件', fileList)
				if (fileList[0] && fileList[0].pkid) {
					this.modelFormData.cover = fileList[0].url
					this.modelFormData.coverPath = fileList[0].path
					this.modelFormData.coverPkid = fileList[0].pkid
					console.log('具体url', this.modelFormData.cover)
				} else {
					console.log('无效')
				}
			},
			leftClick() {
				if (this.pkid) {
					uni.navigateTo({
						url: '/pages/index/detail?pkid=' + this.pkid
					})
					console.log('前往详情')
				} else {
					uni.navigateTo({
						url: '/pages/index/index'
					})
				}
			},
			hideKeyboard() {
				console.log('隐藏键盘')
			},
			submitForm() {
				console.log('将要提交的数据', this.modelFormData)
				this.$refs.uForm.validate().then(res => {
					this.submitFormAction()
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},
			submitFormAction() {
				const vm = this
				vm.submitLoading = true
				uni.request({
					header: {
						Authorization: AuthorizationToken
					},
					method: 'POST',
					url: baseUrl + '/agw/mongodb/table/add',
					data: {
						name: this.modelFormData.name,
						type: this.modelFormData.typeCode,
						cover: [{
							url: this.modelFormData.coverPath,
							pkid: this.modelFormData.coverPkid,
						}],
						ingredients: this.modelFormData.ingredients,
						steps: this.modelFormData.steps,
						remarks: this.modelFormData.remarks,
						tablePkid: '4163d0000b7a4b2990392d5a534b7271',
						pkid: this.pkid || null
					},
					success(res) {
						vm.submitLoading = false
						console.log('返回结果', res)
						const data = res.data
						if(data['code'] === 0) {
							console.log('数据为', data)
							uni.$u.toast('保存成功！')
							uni.navigateTo({
								url: '/pages/index/index'
							})
						}
					},
					fail(e) {
						console.log('err', e)
						vm.submitLoading = false
					}
				})
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
	};
</script>

<style lang="scss">
	.dishes-add {
		box-sizing: border-box;
		padding: 110rpx 20rpx 20rpx 20rpx;

		&-container {
			background-color: #fff;
			padding: 0 20rpx;
			box-sizing: border-box;

			.form-submit-box {
				margin-top: 40rpx;
				padding-bottom: 40rpx;
			}
		}
	}
</style>